package com.css.fxfzxczh.modules.aftershockSequence.scheduleTask;

import cn.hutool.core.date.DateUtil;
import com.css.fxfzxczh.modules.aftershockSequence.entity.AftershockSequence;
import com.css.fxfzxczh.modules.aftershockSequence.entity.RealEarthquakeEntity;
import com.css.fxfzxczh.modules.aftershockSequence.repository.AftershockSequenceRepository;
import com.css.fxfzxczh.modules.aftershockSequence.service.SetEarthquakeMapService;
import com.css.fxfzxczh.modules.buildingKilometerGrid.exceptions.BizException;
import com.css.fxfzxczh.util.Xml2ObjectUtil;
import com.css.fxfzxczh.util.PlatformObjectUtils;
import com.css.fxfzxczh.util.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

/**
 * @Author: xzy
 * @CreateTime: 2024/4/7 14:47
 * @Description:
 */

@Slf4j
@Component
public class NetworkDataScheduleTask {

    @Resource
    private SetEarthquakeMapService setEarthquakeMapService;

    @Resource
    private AftershockSequenceRepository aftershockSequenceRepository;


    @Scheduled(cron = "0 0 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public List<RealEarthquakeEntity> test() throws BizException {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("taiWangRestUrl");
        if (StringUtils.isBlank(url)) {
            throw new BizException("slw-config.properties中未找到配置：taiWangRestUrl");
        }
        List<RealEarthquakeEntity> realEarthquakeList = new LinkedList<>();
        try {
            realEarthquakeList = this.getRealEarthquakeList(url);
            if (realEarthquakeList != null) {
                aftershockSequenceRepository.deleteAll();
                save(realEarthquakeList);
                log.debug("台网地震数据同步成功 {}", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            } else {
                log.error("台网地震数据同步失败，数据为空 {}，url：{}", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), url);
            }
        } catch (ParseException e) {
            log.error("台网数据同步失败，时间格式化异常，url：" + url, e);
        } catch (BizException e1) {
            log.error("台网数据同步失败，" + e1.getMessage() + "，url：" + url, e1);
        } catch (Exception e2) {
            log.error("台网数据同步失败，url：" + url, e2);
        }
        return realEarthquakeList;
    }

    public List<RealEarthquakeEntity> getRealEarthquakeList(String url) throws ParseException, BizException {
        List<RealEarthquakeEntity> realEarthquakeEntities = Xml2ObjectUtil.getRealEarthquakeEntity(url);
        if (realEarthquakeEntities == null) {
            return null;
        }
        for (RealEarthquakeEntity item : realEarthquakeEntities) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long time = sdf.parse(item.getEarthquakeDate()).getTime();
            item.setTime(time);
            List<String> provinceInfo = setEarthquakeMapService.queryProvinceByLonLat(item.getLongitude(), item.getLatitude());
            //  新疆 Lon 80.59   42.78        广州 110.53    20.81
//            if (PlatformObjectUtils.isEmpty(provinceInfo) && item.getFlag().equals("1")) {
//                //国外的
//                item.setProvince(item.getLocation());
//                item.setCity(null);
//                item.setCounty(null);
//                continue;
//            }
//            if (PlatformObjectUtils.isEmpty(provinceInfo) && !item.getFlag().equals("1")) {
//                //中国海域
//                continue;
//            }
            if (PlatformObjectUtils.isEmpty(provinceInfo)) {
                //中国海域
                continue;
            }
            item.setProvince(provinceInfo.get(1));
            List<String> cityInfo = setEarthquakeMapService.queryCityByLonLat(item.getLongitude(), item.getLatitude(),
                    provinceInfo.get(0));
            if (cityInfo.size() > 0) {
                item.setCity(cityInfo.get(1));
                List<String> countyInfo = setEarthquakeMapService.queryCountyByLonLat(item.getLongitude(), item.getLatitude(),
                        cityInfo.get(0));
                if (countyInfo.size() > 0) {
                    item.setCounty(countyInfo.get(1));
                }
            }
        }
        return realEarthquakeEntities;
    }

    public void save(List<RealEarthquakeEntity> list) {
        LinkedList<AftershockSequence> aftershockSequenceList = new LinkedList<>();
        list.stream().forEach(item -> {
            AftershockSequence aftershockSequence = new AftershockSequence();
            BeanUtils.copyProperties(item, aftershockSequence);
            aftershockSequence.setId(UUIDGenerator.getUUID());
            aftershockSequence.setMm(new BigDecimal(item.getMm()));
            aftershockSequence.setLatitude(new BigDecimal(item.getLatitude()));
            aftershockSequence.setLongitude(new BigDecimal(item.getLongitude()));
            aftershockSequence.setEpiDepth(new BigDecimal(item.getEpiDepth()));
            aftershockSequence.setEarthquakeDate(new Date(item.getTime()));
            aftershockSequence.setGeom("POINT(" + aftershockSequence.getLongitude() + " " + aftershockSequence.getLatitude() + ")");
            aftershockSequenceList.add(aftershockSequence);
        });
        aftershockSequenceRepository.batchSave(aftershockSequenceList);
    }
}
